package quq.missq.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import quq.missq.BaseActivity;
import quq.missq.Constants;
import quq.missq.MLog;
import quq.missq.MissQApplication;
import quq.missq.R;
import quq.missq.adapter.TaPagerAdapter;
import quq.missq.beans.MyInformationBean;
import quq.missq.beans.TaPageBean;
import quq.missq.beans.UserBean;
import quq.missq.huanxin.ChatActivity;
import quq.missq.utils.BitmapUtils;
import quq.missq.utils.ImageLoadInterface;
import quq.missq.utils.ImageLoadUtil;
import quq.missq.utils.ImageUtil;
import quq.missq.utils.UserTools;
import quq.missq.utils.VolleyTool;
import quq.missq.views.LoadMoreListView;

/**
 * Created by River on 8/3/15.
 */
public class TaPageActivity extends BaseActivity implements VolleyTool.HTTPListener, LoadMoreListView.OnLoadMore,
        View.OnClickListener {

    private LoadMoreListView mListView;
    private LinkedList<TaPageBean.Result> results;
    private TaPagerAdapter adapter;
    private int maxResults = 10;
    private int currentPage = 1;

    private MyInformationBean bean = null;

    private ImageView mAvatar;
    private TextView mUserName;
    private TextView mUserType;
    private TextView mLevel;
    private TextView mGuanzhuCount;
    private TextView mFensiCount;
    private TextView mTangguoCount;
    private ImageView mGender;

    private ImageView mGuanzhu;
    private ImageView mUnGuanzhu;
    private ImageView mAlbum;
    private ImageView mHuihua;

    private int uid = -1;
    private String username;
    UserBean.User user;
    private LinearLayout llHeadBg;
    private ImageView mBack;
    private ImageView mQa;
    private ImageView mAuth;
    private RelativeLayout mRl_fans;
    private RelativeLayout mRl_concerned;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ta_page_activity);
        uid = getIntent().getExtras().getInt("uid");
        MLog.e(uid+"");
        username = getIntent().getExtras().getString("username");
        user = UserTools.getUser(this);
        initView();
        initListener();
        initPersonalData();
    }

    private void initView() {
        mListView = (LoadMoreListView) findViewById(R.id.listView);
        mGuanzhu = (ImageView) findViewById(R.id.guanzhu);
        mUnGuanzhu = (ImageView) findViewById(R.id.unGuanzhu);
        mAlbum = (ImageView) findViewById(R.id.album);
        mHuihua = (ImageView) findViewById(R.id.huihua);
        mBack = (ImageView) findViewById(R.id.back);
        //图标临时替代
        mQa = (ImageView) findViewById(R.id.qa);
        mAuth = (ImageView) findViewById(R.id.auth);
    }

    private void initListener() {
        mListView.setLoadMoreListen(this);
        mGuanzhu.setOnClickListener(this);
        mUnGuanzhu.setOnClickListener(this);
        mAlbum.setOnClickListener(this);
        mHuihua.setOnClickListener(this);
        mBack.setOnClickListener(this);
        mQa.setOnClickListener(this);
    }

    private void initPersonalData() {
        Map<String, String> params = new HashMap<>();
        params.put("uid", uid + "");
        if (UserTools.getUser(this) != null) {
            params.put("acc_token", UserTools.getUser(this).getAcc_token());
        }
        VolleyTool.get(this, Constants.TA_INFORMATION_URL, params, this, Constants.TA_INFORMATION, MyInformationBean.class);
    }

    private void initCommentData() {
        results = new LinkedList<>();
        adapter = new TaPagerAdapter(this);
        View view = getHeadView();
        mListView.addHeaderView(view);
        adapter.setData(results);
        mListView.setAdapter(adapter);
        loadCommentNetworkData();
    }


    private View getHeadView() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.my_information_head_layout, null);
        initHeadView(view);
        mUserName.setText(bean.getData().getNkname());
        switch (bean.getData().getAuth()) {
            case 0:
                mUserType.setText("普通用户");
                mAuth.setVisibility(View.GONE);
                mQa.setVisibility(View.GONE);
                break;
            case 1:
                mUserType.setText("加V");
                mAuth.setVisibility(View.GONE);
                mQa.setVisibility(View.GONE);
                break;
            case 2:
                mUserType.setText("女神");
                mAuth.setVisibility(View.VISIBLE);
                break;
        }
        guanzhuLogic(bean.getData().getFollowed());
        mLevel.setText("level " + bean.getData().getLevel());
        mGuanzhuCount.setText(bean.getData().getFollows() + "");
        mFensiCount.setText(bean.getData().getFans() + "");
        mTangguoCount.setText(bean.getData().getAccount().getAmountSweet() + "");//糖果数量
        String bgUrl = bean.getData().getBackground();
        if (bgUrl != null && !bgUrl.isEmpty()) {
            ImageLoadUtil.loadBitmapImage(Constants.IMAGE_HOST + bgUrl, new ImageLoadInterface.ImageLoadCallBack() {
                @Override
                public void callBack(Bitmap bitmap) {
                    llHeadBg.setBackgroundDrawable(new BitmapDrawable(bitmap));
                }
            });
//            ImageLoadUtil.loadImage(llHeadBg,Constants.IMAGE_HOST + bgUrl,R.mipmap.f_default_bg);
//            VolleyTool.getImageLoader().get(Constants.IMAGE_HOST + bgUrl, new ImageLoader.ImageListener() {
//                @Override
//                public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
//                    if (imageContainer != null && imageContainer.getBitmap() != null) {
//                        llHeadBg.setBackgroundDrawable(new BitmapDrawable(getResources(), imageContainer.getBitmap()));
//                    }
//                }
//
//                @Override
//                public void onErrorResponse(VolleyError volleyError) {
//
//                }
//            });
        }
        int sex = R.mipmap.boy_icon;
        if (bean.getData().getGender() == 1) {
            sex = R.mipmap.boy_icon;
        } else {
            sex = R.mipmap.girl_icon;
        }
        mGender.setImageResource(sex);
        String avatar = bean.getData().getAvatar();
        if (avatar != null && !avatar.isEmpty()) {
            MLog.e(Constants.IMAGE_HOST + avatar);
            int i = avatar.indexOf('?');
            String substring = avatar.substring(0, i);
            MLog.e(substring);

            ImageLoadUtil.loadBitmapImage(Constants.IMAGE_HOST + substring, new ImageLoadInterface.ImageLoadCallBack() {
                @Override
                public void callBack(Bitmap bitmap) {
                    mAvatar.setBackgroundDrawable(new BitmapDrawable(BitmapUtils.toRoundBitmap(bitmap, 3, R.color.white)));
                }
            });
        }
//        VolleyTool.getImageLoader().get(Constants.IMAGE_HOST + substring, new ImageLoader.ImageListener() {
//            @Override
//            public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
//                if (imageContainer.getBitmap() != null) {
//                    mAvatar.setImageBitmap(BitmapUtils.toRoundBitmap(imageContainer.getBitmap(), 3, R.color.white));
//                }
//            }
//
//            @Override
//            public void onErrorResponse(VolleyError volleyError) {
//
//            }
//        });
        return view;
    }

    private void initHeadView(View view) {
        llHeadBg = (LinearLayout) view.findViewById(R.id.avtarLayout);
        mGender = (ImageView) view.findViewById(R.id.gender);
        mAvatar = (ImageView) view.findViewById(R.id.avatar);
        mUserName = (TextView) view.findViewById(R.id.userName);
        mUserType = (TextView) view.findViewById(R.id.userType);
        mLevel = (TextView) view.findViewById(R.id.level);
        mGuanzhuCount = (TextView) view.findViewById(R.id.guanzhuCount);
        mFensiCount = (TextView) view.findViewById(R.id.fensiCount);
        mTangguoCount = (TextView) view.findViewById(R.id.tangguoCount);
        mAuth = (ImageView) view.findViewById(R.id.auth);
        mRl_concerned = (RelativeLayout) view.findViewById(R.id.rl_concerned);
        mRl_fans = (RelativeLayout) view.findViewById(R.id.rl_fans);
        initHeadListener();
    }

    private void initHeadListener() {
        mAvatar.setOnClickListener(this);
        mRl_concerned.setOnClickListener(this);
        mRl_fans.setOnClickListener(this);
    }

    private void loadCommentNetworkData() {
        Map<String, String> params = new HashMap<>();
        params.put("uid", uid + "");
        params.put("pn", currentPage + "");
        params.put("maxResults", maxResults + "");
        VolleyTool.get(this, Constants.TA_FEEDS_URL, params, this, Constants.TA_FEEDS, TaPageBean.class);
    }

    @Override
    public <T> void onResponse(T t, int requestCode) {
        if (requestCode == Constants.TA_FEEDS) {
            TaPageBean bean = (TaPageBean) t;
            if (bean.getCode() >= 0) {
                LinkedList<TaPageBean.Result> beans = bean.getData().getResults();
                if (currentPage == 1) {
                    adapter.getData().clear();
                    adapter.getData().addAll(0, beans);
                    adapter.notifyDataSetChanged();
                } else {
                    if (beans.size() > 0) {
                        adapter.getData().addAll(beans);
                        adapter.notifyDataSetChanged();
                    } else {
                        if (results.size() > 10) {
                            showToast("已加载完所有");
                        }
                    }
                    mListView.onLoadComplete();
                }
            } else {
                showToast(bean.getMessage());
            }
        } else if (requestCode == Constants.TA_INFORMATION) {
            bean = (MyInformationBean) t;
            guanzhuLogic(bean.getData().getFollowed());
            initCommentData();
        }
    }

    private void guanzhuLogic(int g) {
        if (g == 0) {
            mGuanzhu.setVisibility(View.VISIBLE);
            mUnGuanzhu.setVisibility(View.GONE);
        } else {
            mGuanzhu.setVisibility(View.GONE);
            mUnGuanzhu.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {

    }

    @Override
    public void loadMore() {
        currentPage = currentPage + 1;
        loadCommentNetworkData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //新加的
            case R.id.back:
                finish();
                break;
            case R.id.qa:
                Intent qaIntent = new Intent();
                qaIntent.putExtra("category", 5).putExtra("userName", username).putExtra("userId", uid + "");
                if (UserTools.getUser(this) == null) {

                    qaIntent.setClass(this, LoginActivity.class);
                    startActivity(qaIntent);
                } else {
                    qaIntent.setClass(this, PublishTopicActivity.class);
                    startActivity(qaIntent);
                }
                break;
            case R.id.guanzhu:
            case R.id.unGuanzhu:
                sendRequest(v.getId());
                break;
            case R.id.huihua:
                if (user == null) {
                    Intent intent = new Intent();
                    intent.setClass(this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    startActivity(new Intent(TaPageActivity.this, ChatActivity.class).putExtra("userId", uid + "")
                            .putExtra("username", username).putExtra("avatarPath", bean.getData().getAvatar80()));
                }
                break;
            case R.id.album:
                Intent intent = new Intent();
                intent.putExtra("uid", uid);
                intent.putExtra("username", username);
                intent.setClass(this, TaAlbumActivity.class);
                startActivity(intent);
                break;
            case R.id.avatar:
                Intent intent1 = new Intent();
                intent1.setClass(this, OtherInfoActivity.class);
                intent1.putExtra("OtherInfo_1", bean);
                startActivity(intent1);
                break;
            case R.id.rl_concerned:
                Intent intent2 = new Intent();
                intent2.putExtra("tag", false);
                intent2.putExtra("uid", uid);
                intent2.putExtra("username", username);
                intent2.setClass(this, TaContractorActivity.class);
                startActivity(intent2);
                break;
            case R.id.rl_fans:
                Intent intent3 = new Intent();
                intent3.putExtra("uid", uid);
                intent3.putExtra("username", username);
                intent3.setClass(this, TaFansActivity.class);
                startActivity(intent3);
                break;
        }
    }

    private void sendRequest(int vid) {

        if (user == null) {
            Intent intent = new Intent();
            intent.setClass(this, LoginActivity.class);
            startActivity(intent);
        } else {
            Map<String, String> params = new HashMap<>();
            params.put("uid", uid + "");
            params.put("acc_token", user.getAcc_token());
            String url = "";
            if (vid == R.id.guanzhu) {
                url = Constants.FOLLOW_URL;
                guanzhuLogic(1);
            } else {
                url = Constants.UNFOLLOW_URL;
                guanzhuLogic(0);
            }
            VolleyTool.get(this, url, params, this, 0, null);
        }

    }

}
